/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, { memo, useCallback, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  DeviceEventEmitter,
  EmitterSubscription,
} from 'react-native';
import { Track } from '../model';
import { useBreakpointValue } from '@hadss/react_native_adaptive_layout';
import musicPlayer from '../../util';

interface CurPlaySongProps {
  song: Track;
  setCurrentSong: (song: Track) => void;
  isPlaying: boolean;
  setIsPlaying: (isPlaying: boolean) => void;
  changePageShow: Function;
}

interface ControlIconsTableProps {
  togglePlayPause: () => void;
  isPlaying: boolean;
  playPrevious: () => void;
  playNext: () => void;
}

const ControlIconsPhone = memo(
  ({
    togglePlayPause,
    isPlaying,
  }: {
    togglePlayPause: () => void;
    isPlaying: boolean;
  }) => (
    <View style={styles.phoneStyle}>
      <TouchableOpacity onPress={togglePlayPause}>
        <Image
          source={
            isPlaying
              ? require('../../../../asset/image/pause_icon.png')
              : require('../../../../asset/image/play_icon.png')
          }
          style={styles.iconStyle1}
        />
      </TouchableOpacity>
      <Image
        source={require('../../../../asset/image/play_list_icon.png')}
        style={styles.playListIconStyle}
      />
    </View>
  )
);

const ControlIconsFold = memo(
  ({ togglePlayPause, isPlaying, playPrevious, playNext }: ControlIconsTableProps) => (
    <View style={styles.foldOut}>
      <Image
        source={require('../../../../asset/image/play_mode.png')}
        style={styles.iconStyle1}
      />
      <TouchableOpacity onPress={playPrevious}>
        <Image
          source={require('../../../../asset/image/control_left.png')}
          style={styles.iconStyle2}
        />
      </TouchableOpacity>
      <TouchableOpacity onPress={togglePlayPause}>
        <Image
          source={
            isPlaying
              ? require('../../../../asset/image/pause_icon.png')
              : require('../../../../asset/image/play_icon.png')
          }
          style={styles.iconStyle2}
        />
      </TouchableOpacity>
      <TouchableOpacity onPress={playNext}>
        <Image
          source={require('../../../../asset/image/control_right.png')}
          style={styles.iconStyle2}
        />
      </TouchableOpacity>
      <Image
        source={require('../../../../asset/image/play_list_icon.png')}
        style={styles.iconStyle1}
      />
    </View>
  )
);

const ControlIconsTable = memo(
  ({ togglePlayPause, isPlaying, playPrevious, playNext }: ControlIconsTableProps) => (
    <View style={styles.tableStyle}>
      <View style={styles.tableStyleInner}>
        <Image
          source={require('../../../../asset/image/play_mode.png')}
          style={styles.iconStyle1}
        />
        <TouchableOpacity onPress={playPrevious}>
          <Image
            source={require('../../../../asset/image/control_left.png')}
            style={styles.iconStyle2}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={togglePlayPause}>
          <Image
            source={
              isPlaying
                ? require('../../../../asset/image/pause_icon.png')
                : require('../../../../asset/image/play_icon.png')
            }
            style={styles.iconStyle2}
          />
        </TouchableOpacity>
        <TouchableOpacity onPress={playNext}>
          <Image
            source={require('../../../../asset/image/control_right.png')}
            style={styles.iconStyle2}
          />
        </TouchableOpacity>
        <Image
          source={require('../../../../asset/image/play_list_icon.png')}
          style={styles.iconStyle1}
        />
      </View>
      <View style={styles.flexStyle} />
      <Image
        source={require('../../../../asset/image/love_icon.svg')}
        style={styles.liveIcon}
      />
    </View>
  )
);

const CurPlaySong: React.FC<CurPlaySongProps> = ({
  song,
  setCurrentSong,
  isPlaying,
  setIsPlaying,
  changePageShow,
}) => {
  const togglePlayPause = useCallback(() => {
    if (isPlaying) {
      musicPlayer.pause();
      setIsPlaying(false);
    } else {
      musicPlayer.play();
      setIsPlaying(true);
    }
  }, [isPlaying, setIsPlaying]);

  const playTrack = useCallback(
    (direction: 'previous' | 'next') => {
      if (direction === 'previous') {
        musicPlayer.previousTrack();
      } else {
        musicPlayer.nextTrack();
      }

      const currentSong = musicPlayer.getCurrentTrack();
      if (currentSong) {
        setCurrentSong(currentSong);
        setIsPlaying(true);
      }
    },
    [setCurrentSong]
  );

  useEffect(() => {
    const track = musicPlayer.getCurrentTrack();
    let listener: EmitterSubscription | null = null;
    musicPlayer.setOnTrackChange((currentTrack) => {
      setCurrentSong(currentTrack);
    });
    musicPlayer.setOnStatusChange((isPlaying) => {
      setIsPlaying(isPlaying);
    });

    listener = DeviceEventEmitter.addListener('trackChange', () => {
      if (track) {
        setCurrentSong(track);
      }
    });

    if (track) {
      setCurrentSong(track);
    }
    setIsPlaying(musicPlayer.getCurrentStatus());
    return () => {
      listener?.remove();
    };
  }, []);

  const controlIcons = useBreakpointValue({
    base: (
      <ControlIconsPhone
        togglePlayPause={togglePlayPause}
        isPlaying={isPlaying}
      />
    ),
    md: (
      <ControlIconsFold
        togglePlayPause={togglePlayPause}
        isPlaying={isPlaying}
        playPrevious={(): void => playTrack('previous')}
        playNext={(): void => playTrack('next')}
      />
    ),
    lg: (
      <ControlIconsTable
        togglePlayPause={togglePlayPause}
        isPlaying={isPlaying}
        playPrevious={(): void => playTrack('previous')}
        playNext={(): void => playTrack('next')}
      />
    ),
    xl: (
      <ControlIconsTable
        togglePlayPause={togglePlayPause}
        isPlaying={isPlaying}
        playPrevious={(): void => playTrack('previous')}
        playNext={(): void => playTrack('next')}
      />
    ),
  });

  const curPlaySongInfo = useBreakpointValue({
    base: 155,
    sm: 155,
    md: 155,
    lg: 384,
    xl: 384,
  });

  const bottomDistance = useBreakpointValue({
    sm: 0,
    md: 15,
  });

  return (
    <TouchableOpacity
      onPress={(): void => {
        changePageShow(false);
      }}
      style={[styles.curPlaySongContainer, { marginBottom: bottomDistance }]}
    >
      <Image
        source={require('../../../../asset/image/cover.png')}
        style={styles.albumCover}
      />
      <View style={[styles.songInfo, { width: curPlaySongInfo }]}>
        <Text style={styles.songTitle}>{song.title}</Text>
        <Text style={styles.songArtist}>{song.artist}</Text>
      </View>
      <View style={styles.flexStyle} />
      {controlIcons}
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  curPlaySongContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 8,
    height: 48,
    backgroundColor: 'white',
    marginLeft: 8,
    marginRight: 8,
  },
  albumCover: {
    width: 32,
    height: 32,
    borderRadius: 4,
    marginLeft: 8,
  },
  songInfo: {
    flexDirection: 'column',
    justifyContent: 'center',
    left: 8,
  },
  songTitle: {
    fontSize: 14,
    fontWeight: '500',
    lineHeight: 19,
    color: 'rgba(0, 0, 0, 0.9)',
  },
  songArtist: {
    fontSize: 10,
    color: 'rgba(0, 0, 0, 0.4)',
    lineHeight: 13,
  },
  flexStyle: {
    flex: 1,
  },
  iconStyle1: {
    width: 24,
    height: 24,
  },
  iconStyle2: {
    width: 28,
    height: 28,
  },
  playListIconStyle: {
    width: 24,
    height: 24,
    marginLeft: 16,
  },
  foldOut: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'space-between',
    marginRight: 24,
    width: 212,
  },
  phoneStyle: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    flex: 1,
  },
  tableStyle: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  tableStyleInner: {
    position: 'absolute',
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: 310,
    left: -350,
  },
  liveIcon: {
    width: 24,
    height: 24,
    marginRight: 8,
  },
});

export default CurPlaySong;
